package com.simen.connectandroid.command;

import com.simen.connectandroid.command.utils.CommandCreator;
import com.simen.connectandroid.model.Application;
import com.simen.connectandroid.model.Device;
import com.simen.hellobytes.runtime.RuntimeHelper;

/**
 * 获取当前显示的Activity及所属App包名
 * Created on 2021/11/18 13:17.
 *
 * @author Simen
 */
public class GetTopAppInfoCommand extends AdbCommand<GetTopAppInfoCommand> {

    private boolean commandResult;
    private boolean deviceIsLocked;
    private Application topApp;

    public GetTopAppInfoCommand(){
    }

    public GetTopAppInfoCommand(Device device) {
        super(device);
    }

    @Override
    public GetTopAppInfoCommand exec() {
        RuntimeHelper runtimeHelper = RuntimeHelper.create(CommandCreator.createAdb()
                .appendAdbDevice(device)
                .appendParam("shell dumpsys window")
                //.appendParam("shell dumpsys window | findstr mCurrentFocus")
                //.appendParam("shell dumpsys activity | findstr mFocusedActivity")
                .build());
        runtimeHelper.exec();

        commandResult = runtimeHelper.getProcessCode() == 0;
        log = runtimeHelper.getOutputLog();

        if (execResult()) {
            String[] lines = log.split("\n");
            if (lines.length > 1) {
                for (int i = 0; i < lines.length; i++) {
                    String line = lines[i].trim();
                    if (line.startsWith("mCurrentFocus=Window")) {
                        String body = line.replace("{", "").replace("}", "");
                        String[] topAppInfo = RuntimeHelper.splitCommand(body);
                        if (topAppInfo.length == 3) {
                            if ("StatusBar".equals(topAppInfo[2])) {
                                deviceIsLocked = true;
                            } else if (topAppInfo[2].contains("/")) {
                                String[] array = topAppInfo[2].split("/");
                                topApp = new Application(array[1], array[0]);
                            } else {
                                System.out.println("unknown app: " + body);
                            }
                        }
                    }
                }
            }
        }

        return this;
    }

    @Override
    public boolean execResult() {
        return commandResult && log.contains("mCurrentFocus=");
    }

    public boolean isDeviceIsLocked() {
        return deviceIsLocked;
    }

    public Application getTopApp() {
        return topApp;
    }
}
